package com.sky.service.impl;

import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.service.ShoppingCartService;
import com.sky.vo.DishItemVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {

    @Autowired
    private DishMapper dishMapper;
    private ShoppingCartMapper shoppingCartMapper;
    private SetmealMapper setmealMapper;

    @Override
    public void addCart(ShoppingCartDTO dto) {
        ShoppingCart shoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(dto, shoppingCart);//倒进去已有的属性值

        //判断购物车中商品数量
        shoppingCart.setUserId(BaseContext.getCurrentId());
        ShoppingCart cart = shoppingCartMapper.selectBy(shoppingCart);
        if(cart != null){

            //补缺失字段
            //dish查
            if(dto.getDishId() != null){
                Dish dish = dishMapper.getById(dto.getDishId());
                shoppingCart.setName(dish.getName());
                shoppingCart.setImage(dish.getImage());
                shoppingCart.setAmount(dish.getPrice());
 //商品数应该根据购物车中是否存在来决定
            } else if (dto.getSetmealId()!=null) {
                Setmeal setmeal = (Setmeal) setmealMapper.getDishItemBySetmealId(dto.getSetmealId());
                shoppingCart.setName(setmeal.getName());
                shoppingCart.setImage(setmeal.getImage());
                shoppingCart.setAmount(setmeal.getPrice());

            }
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCart.setNumber(1);

            //存数据
            shoppingCartMapper.insert(shoppingCart);
        } else {
            cart.setNumber(cart.getNumber()+1);
            shoppingCartMapper.update(cart);
        }

        //补缺失字段
            //dish查
        if(dto.getDishId() != null){
            Dish dish = dishMapper.getById(dto.getDishId());
            shoppingCart.setName(dish.getName());
            shoppingCart.setImage(dish.getImage());
            shoppingCart.setAmount(dish.getPrice());
            shoppingCart.setCreateTime(LocalDateTime.now());
//            shoppingCart.setNumber(1);   商品数应该根据购物车中是否存在来决定
        } else if (dto.getSetmealId()!=null) {
            
        }
    }

    /**
     * 列出当前用户的所有购物车项。
     *
     * @return 购物车项列表
     */
    @Override
    public List<ShoppingCart> list() {
        return shoppingCartMapper.list(BaseContext.getCurrentId());
    }
/**
     * 清空当前用户的购物车。
     */
    @Override
    public void clean() {
        shoppingCartMapper.delete(BaseContext.getCurrentId());
    }
}
